const login = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../module/resModel')
const { get, set } = require('../db/myredis')

const userRouter = async (req, res) => {
  //根据不通的路由匹配对应的controller层
  const path = req.path
  const method = req.method
  res.setHeader('Content-Type', 'application/json')

  // 注意📢 method 大小写 先修改为get方便测试
  if (path === '/api/user/login' && method === 'GET') {
    const { username, password } = req.query
    if (!username || !password) {
      return new ErrorModel('用户名或密码不能为空')
    }
    {
      let resVal = await login(username, password)
      if (resVal) {
        req.session[req.cookie.userId] = {}
        req.session[req.cookie.userId]['username'] = username
        req.session[req.cookie.userId]['password'] = password
        await set(req.cookie.userId, JSON.stringify(req.sessions))
        return new SuccessModel(resVal)
      } else {
        return new ErrorModel('用户名或密码错误!!!')
      }
    }
  }
  // 判断只要存在cookie 就登录成功
  if (path === '/api/user/cookie-test' && method === 'GET') {
    let userId = req.cookie.userId
    let resVal = await get(userId)
    if (resVal) {
      resVal = resVal[userId]
    }
    if (resVal?.username) {
      return new SuccessModel('登录成功')
    } else return new ErrorModel('登录失败')
  }
  return false
}

module.exports = userRouter
